<template>
  <nut-config-provider :theme="theme" :theme-vars="themeVars">
    <view :style="{backgroundColor: themeVars.pageBackgroundColor,padding: themeVars.pagePadding,height: '100vh'}">

      <nut-form
          ref="formRef"
          :model-value="formData"
          :rules="formRule"

      >
        <nut-form-item label="公司名称" prop="name">
          <nut-input
              v-model="formData.name"
              placeholder="请输入公司名称"
              type="text"
          />
        </nut-form-item>
        <nut-form-item label="经营类型" prop="productCategoryName">
          <nut-input
              v-model="formData.productCategoryName"
              placeholder="请输入经营类型"
              type="text"
              @click="clickCategory"
          >
            <template #right>
              <IconFont size="10"
                        name="rect-right"></IconFont>
            </template>
          </nut-input>
        </nut-form-item>


        <nut-form-item label="联系人员" prop="contactName">
          <nut-input
              v-model="formData.contactName"
              placeholder="请输入联系人员"
              type="text"
          />
        </nut-form-item>
        <nut-form-item label="联系电话" prop="contactPhone">
          <nut-input
              v-model="formData.contactPhone"
              placeholder="请输入联系电话"
              type="text"
          />
        </nut-form-item>
        <nut-form-item label="详细地址" prop="addrDetail">
          <nut-input v-model="formData.addrDetail" placeholder="请输入详细地址" @click="selectLocation" type="text">
            <template #right>
              <IconFont

                  size="18"
                  name="location2"
                  color="red"
              ></IconFont>
            </template>
          </nut-input>
        </nut-form-item>


        <nut-form-item label="微信二维码" prop="wechatQrcode">
          <nut-uploader
              v-model:file-list="formData.wechatQrcode"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="9"
              multiple
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
              const resData = JSON.parse(data.data)
              fileItem.url = resData.data
                console.log('success',data,fileItem)
              }"
              @failure="({data,fileItem, option,responseText})=>{
                  const resData = JSON.parse(data.data)
                  Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
              }"

          >
          </nut-uploader>
        </nut-form-item>


        <nut-form-item label="企业介绍" prop="enterpriseDesc">
          <nut-textarea v-model="formData.enterpriseDesc" placeholder="请输入企业介绍"  type="text"/>

        </nut-form-item>
        <nut-form-item label="企业Logo" prop="enterpriseLogo">
          <nut-uploader
              v-model:file-list="formData.enterpriseLogo"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="9"
              multiple
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
                      const resData = JSON.parse(data.data)
                      fileItem.url = resData.data
                        console.log('success',data,fileItem)
                      }"
              @failure="({data,fileItem, option,responseText})=>{
                          const resData = JSON.parse(data.data)
                          Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
                      }"

          >
          </nut-uploader>
        </nut-form-item>
        <nut-form-item label="企业资质" prop="enterpriseQualis">
          <nut-uploader
              v-model:file-list="formData.enterpriseQualis"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="9"
              multiple
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
                      const resData = JSON.parse(data.data)
                      fileItem.url = resData.data
                        console.log('success',data,fileItem)
                      }"
              @failure="({data,fileItem, option,responseText})=>{
                          const resData = JSON.parse(data.data)
                          Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
                      }"

          >
          </nut-uploader>
        </nut-form-item>
        <nut-form-item label="企业场景" prop="enterpriseScene">
          <nut-uploader
              v-model:file-list="formData.enterpriseScene"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="9"
              multiple
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
                      const resData = JSON.parse(data.data)
                      fileItem.url = resData.data
                        console.log('success',data,fileItem)
                      }"
              @failure="({data,fileItem, option,responseText})=>{
                          const resData = JSON.parse(data.data)
                          Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
                      }"

          >
          </nut-uploader>
        </nut-form-item>
      </nut-form>


      <view class="fixed-bottom">
        <nut-button type="primary" style="width: 200px" @click="submit">保存</nut-button>
      </view>
    </view>
    <nut-action-sheet
        v-model:visible="show"
        title="选择厂家类型"
        :menu-items="busiTypeList"
        option-tag="name"
        choose-tag-value="id"
        cancel-txt="取消"
        description=""
        @choose="choose"
        style="overflow:hidden"
    />
  </nut-config-provider>

</template>

<script setup>
import {reactive, ref, toRaw} from 'vue';
import {IconFont} from '@nutui/icons-vue'
import useTheme from "../../../hooks/useTheme";
import Taro from "@tarojs/taro";
import {Phone1Reg} from "../../../utils/regUtils";
import getBaseUrl from "../../../network/baseUrl";
import {Api} from "../../../api/dev";
import {twProductCategoryPage} from "../../../api/productCategory";
import {twEnterpriseMyDetail, twEnterpriseMyEdit} from "../../../api/enterprise";
import {getFileName} from "../../../utils/strUtils";
import {cloneDeep} from "lodash";


const {theme, themeVars} = useTheme()
const token = Taro.getStorageSync('token')
const baseUrl = getBaseUrl()
const returnUrl = Api.fileUploadDynamicReturnUrl


const formData = ref({
  name: '',
  productCategoryId: '',
  productCategoryName: '',
  enterpriseLogo: [],
  contactName: '',
  contactPhone: '',
  qualifications: [],
  wechatQrcode: [],
  enterpriseQualis: [],
  enterpriseScene: [],
  enterpriseDesc: '',
  addrDetail: ''

})
const formRule = {
  name: [{required: true, message: '请填写厂家名称'},],
  productCategoryName: [{required: true, message: '请选择经营类型'},],
  wechatQrcode: [{required: true, message: '请上传微信二维码'},
    {
      validator: (val) => {
        const list = toRaw(val)
        return new Promise((resolve, reject) => {
          if (list.length <= 0) {
            reject('请上传微信二维码')
          } else {
            resolve('')
          }
        })
      }
    }
  ],
  enterpriseDesc: [{required: true, message: '请填写企业介绍'},],
  addrDetail: [{required: true, message: '请填写公司地址'},],
  enterpriseLogo: [{required: true, message: '请上传Logo'},
    {
      validator: (val) => {
        const list = toRaw(val)
        return new Promise((resolve, reject) => {
          if (list.length <= 0) {
            reject('请上传Logo')
          } else {
            resolve('')
          }
        })
      }
    }
  ],
  enterpriseQualis: [{required: true, message: '请上传企业资质'},
    {
      validator: (val) => {
        const list = toRaw(val)
        return new Promise((resolve, reject) => {
          if (list.length <= 0) {
            reject('请上传企业资质')
          } else {
            resolve('')
          }
        })
      }
    }
  ],
  enterpriseScene: [{required: true, message: '请上传企业场景'},
    {
      validator: (val) => {
        const list = toRaw(val)
        return new Promise((resolve, reject) => {
          if (list.length <= 0) {
            reject('请上传企业场景')
          } else {
            resolve('')
          }
        })
      }
    }
  ],
  contactName: [{required: true, message: '请填写联系人姓名'},],
  contactPhone: [{required: true, message: '请填写联系人电话'}, {
    validator: (val) => {
      return new Promise((resolve, reject) => {
        if (!Phone1Reg.test(val)) {
          reject('联系电话格式不正确')
        } else {
          resolve('')
        }
      })
    }
  }],
}

const selectLocation = () => {
  console.log('selectLocation')

//获取位置
  Taro.getLocation({
    type: 'gcj02',
    altitude: true,
    isHighAccuracy: true,
    success: function (res) {
      Taro.chooseLocation({
        latitude: +res.latitude,
        longitude: +res.longitude,
        success(res) {
          console.log("chooseLocation", res)
          const {
            address,
            errMsg,
            latitude,
            longitude,
            name
          } = res
          // 根据经纬度获取省市区
          formData.value.addrDetail = address
          formData.value.addrLnglat = `${longitude},${latitude}`
        }
      })
    },
    fail: function (rr) {
      console.error("getLocation fail", rr)
      Taro.getSetting({
        success: res => {
          if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
            // 用户拒绝了授权
            Taro.showModal({
              title: '提示',
              content: '您拒绝了定位权限，将无法选择地址，修改位置消息',
              success: res => {
                console.log("showModal ", res)
                if (res.confirm) {
                  // 跳转设置页面
                  Taro.openSetting({
                    success: res => {
                      if (res.authSetting['scope.userLocation']) {
                        // 授权成功，重新定位
                        Taro.getLocation({
                          success: res => {

                            console.log("位置信息 ", res)
                          }
                        });
                      } else {
                        // 没有允许定位权限
                        Taro.showToast({
                          title: '您拒绝了定位权限，将无法选择地址，修改位置消息',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
          }
        }
      })
    }
  })
}
const formRef = ref(null)

const reset = () => {
  formRef.value?.reset()
}


const busiTypeList = ref([]);
const getProductCategoryPage = () => {
  twProductCategoryPage({current: 1, size: 1000, level: 1,status:'ENABLE'}).then(res => {
    busiTypeList.value = res.data.records
  })
}
getProductCategoryPage()


const submit = () => {
  formRef.value?.validate().then(({valid, errors}) => {
    if (valid) {
      console.log('success:', formData.value)
      const data = cloneDeep(formData.value)
      if (data.wechatQrcode.length > 0) {
        data.wechatQrcode = data.wechatQrcode.map(e => e.url).join(",")
      }
      if (data.enterpriseLogo.length > 0) {
        data.enterpriseLogo = data.enterpriseLogo.map(e => e.url).join(",")
      }
      if (data.enterpriseScene.length > 0) {
        data.enterpriseScene = data.enterpriseScene.map(e => e.url).join(",")
      }
      if (data.enterpriseQualis.length > 0) {
        data.enterpriseQualis = data.enterpriseQualis.map(e => e.url).join(",")
      }
      console.log("data", data)
      twEnterpriseMyEdit(data).then(res => {
        if (res.code == 200) {
          Taro.showToast({title: res.msg, icon: 'success', duration: 1500,});
          getEnterpriseMyDetail()
        }
      }).finally(()=>{
        Taro.hideLoading();
      })
    } else {
      console.warn('error:', errors)
    }
  })
}


const show = ref(false)
const clickCategory = () => {
  console.log("formData.value.productCategoryId", formData.value.productCategoryId)
  busiTypeList.value.forEach(item => {
    console.log("item", item)
    if (item.id == formData.value.productCategoryId || '') {
      item.color = 'red'
    } else {
      item.color = 'black'
    }
  })
  show.value = true;
}

const choose = (item) => {
  console.log(item)
  formData.value.productCategoryId = item.id
  formData.value.productCategoryName = item.name
}

const getEnterpriseMyDetail = () => {
  twEnterpriseMyDetail().then(res => {
    console.log("twEnterpriseMyDetail", res)
    if (200 == res.code) {
      if (res.data) {
        formData.value = res.data
        if (res.data.wechatQrcode) {
          formData.value.wechatQrcode = res.data.wechatQrcode.split(',').map(url => {
            const img = {
              name: getFileName(url),
              url: url,
              status: 'success',
              message: '上传成功',
              type: 'image'
            }
            return img;
          })
        } else {
          formData.value.wechatQrcode = []
        }

        if (res.data.enterpriseLogo) {
          formData.value.enterpriseLogo = res.data.enterpriseLogo.split(',').map(url => {
            const img = {
              name: getFileName(url),
              url: url,
              status: 'success',
              message: '上传成功',
              type: 'image'
            }
            return img;
          })
        } else {
          formData.value.enterpriseLogo = []
        }

        if (res.data.enterpriseQualis) {
          formData.value.enterpriseQualis = res.data.enterpriseQualis.split(',').map(url => {
            const img = {
              name: getFileName(url),
              url: url,
              status: 'success',
              message: '上传成功',
              type: 'image'
            }
            return img;
          })
        } else {
          formData.value.enterpriseQualis = []
        }

        if (res.data.enterpriseScene) {
          formData.value.enterpriseScene = res.data.enterpriseScene.split(',').map(url => {
            const img = {
              name: getFileName(url),
              url: url,
              status: 'success',
              message: '上传成功',
              type: 'image'
            }
            return img;
          })
        } else {
          formData.value.enterpriseScene = []
        }
      } else {
        Taro.redirectTo({url:'/pages/view/settleForm/index'})
      }
    }
  })
}
getEnterpriseMyDetail()

</script>

<style>
.fixed-bottom {
  position: fixed;
  bottom: 30px;
  left: 0;
  display: flex;
  justify-content: center;
  width: 100%;
}


</style>